package netty.tcp.reveive;

import com.zetas.option.push.message.sdk.PushSDKMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import netty.common.network.Message;
import netty.tcp.websocket.MessageContainer;
import netty.tcp.websocket.Session;
import netty.tcp.websocket.SessionManager;
import test.PerformanceAnalyze;

import java.time.Instant;

public class ServerHandler extends SimpleChannelInboundHandler<Message> {

    static PerformanceAnalyze performanceAnalyze = new PerformanceAnalyze();

    public ServerHandler() {
        System.out.println("ServerHandler create");
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
        PushSDKMessage.Message4Head message4Head = PushSDKMessage.Message4Head.parseFrom(msg.getHead());

        MessageContainer messageContainer = new MessageContainer(
                message4Head.getPublishTime(),
                message4Head.getCreationTime(),
                Integer.parseInt(message4Head.getUserId()),
                message4Head.getChannel(),
                msg.getBody());

        Session session = SessionManager.instance().findByChannelId(messageContainer.getUserId());
        if (session != null) {
            session.send(messageContainer);
        } else {
            msg.getBody().release();
        }

        performanceAnalyze.meter();
        performanceAnalyze.delay(Instant.now().getNano() - message4Head.getPublishTime());
        performanceAnalyze.length(msg.bodyLength());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx){
//        System.out.println("server 读取数据完毕..");
//        ctx.flush();//刷新后才将数据发出到SocketChannel

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        ctx.channel().close();
    }

}
